/* beautify ignore:start */
import {Component, Input, OnInit, Output, EventEmitter, OnChanges, SimpleChange, ChangeDetectorRef} from '@angular/core';
/* beautify ignore:end */

const paginationConfig: any = {
    maxSize: 5,
    itemsPerPage: 15,
    boundaryLinks: false,
    directionLinks: true,
    firstText: '首页',
    previousText: '上一页',
    nextText: '下一页',
    lastText: '尾页',
    rotate: false
};

@Component({
    selector: 'pagination',
    styleUrls: ['pagination.component.css'],
    templateUrl: 'pagination.component.html'
})
export class PaginationComponent implements OnInit, OnChanges {
    @Input() public maxSize: number;    // 显示最大页数
    @Input() public boundaryLinks: boolean;  // 显示首页尾页
    @Input() public directionLinks: boolean; // 显示上一页下一页
    @Input() public rotate: boolean;     // 应该是显示省略号 true 是不显示 false 显示省略号
    @Input() public selectSize: boolean;    // 显示选择每页行数
    @Input() public viewRedirct: boolean;      // 显示跳转页面

    @Input() private disabled: boolean;  // 禁用
    private _inited: boolean = false;   // 初始化
    private _page: number;  // 当前页
    private _totalPages: number; // 最大页数
    private _totalItems: number; // 最大行数
    private _itemsPerPage: number; // 每页行数
    private pages: Array<any>;  // 分页对象
    private _redirctPage: any;

    @Output() public pageChanged: EventEmitter<any> = new EventEmitter(); // 跳转页面
    //@Output() private numPages: EventEmitter<any> = new EventEmitter(); // 计算完当前有多少页

    constructor(private _changeDetectionRef: ChangeDetectorRef) {

    }

    //START get/set page
    public set page(value) {
        const _previous = this._page;
        this._page = (value > this.totalPages) ? this.totalPages : (value || 1);

        if (_previous === this._page || typeof _previous === 'undefined') {
            return;
        }

        this.pageChanged.emit({
            page: this._page,
            itemsPerPage: this.itemsPerPage
        });
    }
    public get page() {
        return this._page;
    }
    //END

    //START get/set totalPages
    public set totalPages(v: number) {
        this._totalPages = v;
        //this.numPages.emit(v);
        if (this._inited) {
            this.selectPage(this.page);
        }
    }
    public get totalPages() {
        return this._totalPages;
    }
    //END

    // START get/set totalItems
    @Input() public get totalItems(): number {
        return this._totalItems;
    }
    public set totalItems(v: number) {
        this._totalItems = v;
        this.totalPages = this.calculateTotalPages();
    }
    // END

    // START get/set itemsPerPage
    @Input() public get itemsPerPage(): number {
        return this._itemsPerPage;
    }
    public set itemsPerPage(v: number) {
        this._itemsPerPage = v;
        this.totalPages = this.calculateTotalPages();
    }
    // END

    // 初始化
    ngOnInit() {
        this.maxSize = typeof this.maxSize !== 'undefined' ? this.maxSize : paginationConfig.maxSize;
        this.rotate = typeof this.rotate !== 'undefined' ? this.rotate : paginationConfig.rotate;
        this.boundaryLinks = typeof this.boundaryLinks !== 'undefined' ? this.boundaryLinks : paginationConfig.boundaryLinks;
        this.directionLinks = typeof this.directionLinks !== 'undefined' ? this.directionLinks : paginationConfig.directionLinks;

        this.itemsPerPage = typeof this.itemsPerPage !== 'undefined' ? this.itemsPerPage : paginationConfig.itemsPerPage;
        this.totalPages = this.calculateTotalPages();
        this.page = 1;
        this.pages = this.getPages(this.page, this.totalPages);
        this._inited = true;
    }

    // 属性变化
    ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
        for (let propName in changes) {
            // 总条数变更
            if ('totalItems' === propName) {
                this.totalItems = changes[propName].currentValue;
            }
        }
    }

    // 是否有上一页
    private noPrevious(): boolean {
        return this.page === 1;
    }

    // 是否下一页
    private noNext(): boolean {
        return this.page === this.totalPages;
    }

    // 跳转某页
    private selectPage(page: number, event?: MouseEvent) {
        if (event) {
            event.preventDefault();
        }

        if (!this.disabled) {
            if (event && event.target) {
                let target: any = event.target;
                target.blur();
            }
            this.writeValue(page);
        }
    }

    // 重新设置分页对象
    private writeValue(value: number) {
        this.page = value;
        this.pages = this.getPages(this.page, this.totalPages);
        //this._changeDetectionRef.detectChanges();

    }

    // 计算最多页数
    private calculateTotalPages(): number {
        let totalPages = this.itemsPerPage < 1 ? 1 : Math.ceil(this.totalItems / this.itemsPerPage);
        return Math.max(totalPages || 0, 1);
    }

    // 设置分页对象,用于模板中
    private makePage(index: number, text: string, isActive: boolean): any {
        return {
            number: index,
            text: text,
            active: isActive
        };
    }

    // 获取当前显示的页数
    private getPages(currentPage: number, totalPages: number): Array<any> {
        let pages: any[] = [];

        // 默认设置
        let startPage = 1;
        let endPage = totalPages;
        let isMaxSized = typeof this.maxSize !== 'undefined' && this.maxSize < totalPages;

        if (isMaxSized) {
            if (this.rotate) {
                // Current page is displayed in the middle of the visible ones
                startPage = Math.max(currentPage - Math.floor(this.maxSize / 2), 1);
                endPage = startPage + this.maxSize - 1;

                // Adjust if limit is exceeded
                if (endPage > totalPages) {
                    endPage = totalPages;
                    startPage = endPage - this.maxSize + 1;
                }
            } else {
                // Visible pages are paginated with maxSize
                startPage = ((Math.ceil(currentPage / this.maxSize) - 1) * this.maxSize) + 1;

                // Adjust last page if limit is exceeded
                endPage = Math.min(startPage + this.maxSize - 1, totalPages);
            }
        }

        // Add page number links
        for (let index = startPage; index <= endPage; index++) {
            let page = this.makePage(index, index.toString(), index === currentPage);
            pages.push(page);
        }

        // Add links to move between page sets
        if (isMaxSized && !this.rotate) {
            if (startPage > 1) {
                let previousPageSet = this.makePage(startPage - 1, '...', false);
                pages.unshift(previousPageSet);
            }

            if (endPage < totalPages) {
                let nextPageSet = this.makePage(endPage + 1, '...', false);
                pages.push(nextPageSet);
            }
        }

        return pages;
    }

    private getText(key: string): string {
        return paginationConfig[key + 'Text'];
    }

    // 判断时候有没有数据
    private hasRow() {
        return this._totalItems > 0;
    }

    //改变行数
    private changeSize(event: any) {
        this.itemsPerPage = parseInt(event.target.value);
        this.selectPage(1);
        this.pageChanged.emit({
            page: this._page,
            itemsPerPage: this.itemsPerPage
        });
    }

    private onGoPage() {
        let num = parseInt(this._redirctPage);
        if (num > 0 && num <= this.totalPages) {
            this.selectPage(num);
        }
        this._redirctPage = '';
    }
}